package com.wx.commons.utils;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.util.Base64;

public class FileEncryptDecryptUtil {


    private static final String KEY = "iamkeyeeddzasdfs"; // 实际应用中应使用更安全的密钥生成方式

    public static void main(String[] args) throws Exception {
        // 示例：加密文件
//        encryptFile("D:\\lib\\resource\\1.mp4", "D:\\lib\\resource\\m1");

        // 解密文件
        decryptFile("D:\\lib\\resource\\m1", "D:\\lib\\resource\\1.mp4");
    }

    public static void encryptFile(String sourcePath, String encryptedPath) throws Exception {
        Cipher cipher = initCipher(Cipher.ENCRYPT_MODE);
        try (FileInputStream fis = new FileInputStream(sourcePath);
             FileOutputStream fos = new FileOutputStream(encryptedPath);
             CipherOutputStream cos = new CipherOutputStream(fos, cipher)) {

            byte[] buffer = new byte[1024];
            int read;
            while ((read = fis.read(buffer)) != -1) {
                cos.write(buffer, 0, read);
            }
        }
        System.out.println("加密完成");
    }

    public static void decryptFile(String encryptedPath, String decryptedPath) throws Exception {
        Cipher cipher = initCipher(Cipher.DECRYPT_MODE);
        try (FileInputStream fis = new FileInputStream(encryptedPath);
             CipherInputStream cis = new CipherInputStream(fis, cipher);
             FileOutputStream fos = new FileOutputStream(decryptedPath)) {

            byte[] buffer = new byte[1024];
            int read;
            while ((read = cis.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
        }
        System.out.println("解密完成");
    }

    private static Cipher initCipher(int mode) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128,new SecureRandom(KEY.getBytes()));
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] codeFormat = secretKey.getEncoded();
        SecretKeySpec keySpec = new SecretKeySpec(codeFormat, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(mode,keySpec);

//        // 生成并保存IV，仅在加密时执行
//        if (mode == Cipher.ENCRYPT_MODE && SAVED_IV == null) {
//            cipher.init(mode, secretKey);
////            AlgorithmParameters params = cipher.getParameters();
////            SAVED_IV = params.getParameterSpec(IvParameterSpec.class).getIV();
////            System.out.println("Generated IV: " + Base64.getEncoder().encodeToString(SAVED_IV));
//        } else { // 解密时使用保存的IV
//            cipher.init(mode, secretKey);
//        }
        return cipher;
    }

}
